<template>
  <el-dialog
      top="10vh"
      width="700px"
      fullscreen
      title="添加/编辑点位"
      :visible.sync="dialogValue"
      :close-on-click-modal="false"
      append-to-body
  >
    <SubmitForm
        :rule-form="ruleForm"
        :rules="rules"
        :form-list="formList"
        @change="handleFormChange"
        @save="onSave"
        @close="dialogValue = false"
    />

  </el-dialog>
</template>

<script>
import {http} from '@/api'

export default {
  name: 'PointAdd',
  data() {
    return {
      apiKey: 'point',
      dialogValue: false,
      ruleForm: {},
      defaultForm: {
        name: '',
        latitude: '',
        longitude: '',
        content: '',
        icon: ''
      },
      rules: {
        name: [{required: true, message: '点位名称不能为空'}],
        latitude: [
          {required: true, message: '纬度不能为空'},
          {pattern: /^-?([1-8]?[0-9](\.[0-9]+)?|90(\.0+)?)$/, message: '纬度格式不正确，范围应在-90到90之间'}
        ],
        longitude: [
          {required: true, message: '经度不能为空'},
          {pattern: /^-?((1[0-7][0-9]|[1-9]?[0-9])(\.[0-9]+)?|180(\.0+)?)$/, message: '经度格式不正确，范围应在-180到180之间'}
        ],
        content: [{required: true, message: '内容描述不能为空'}]
      },
      formList: [
        {
          label: '图标',
          prop: 'icon',
          name: 'file',
          placeholder: '请选择图标文件',
          colSpan: 24
        },
        {
          label: '点位名称',
          prop: 'name',
          name: 'input',
          placeholder: '请输入点位名称',
          colSpan: 24
        },
        {
          label: '纬度',
          prop: 'latitude',
          name: 'input',
          placeholder: '请输入纬度，如：39.9042',
          colSpan: 12
        },
        {
          label: '经度',
          prop: 'longitude',
          name: 'input',
          placeholder: '请输入经度，如：116.4074',
          colSpan: 12
        },
        {
          label: '内容描述',
          prop: 'content',
          name: 'rich',
          placeholder: '请输入点位内容描述',
          colSpan: 24,
          rows: 4
        }
      ]
    }
  },
  methods: {
    handleFormChange({key, val}) {
      this.ruleForm[key] = val;
    },
    open(row) {
      this.dialogValue = true
      if (row) {
        http[this.apiKey].read(row.id).then(res => {
          this.ruleForm = {
            ...res.data,
          }
        })
      } else {
        this.ruleForm = {
          ...this.defaultForm
        }
      }
    },
    onSave() {
      http[this.apiKey][this.ruleForm.id ? 'update' : 'create'](this.ruleForm.id, {
        ...this.ruleForm,
      }).then(res => {
        this.$message.success('操作成功')
        this.dialogValue = false
        this.$emit('get-page')
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
